package com.xxxy.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxy.dao.ExaminationPaperDao;
import com.xxxy.dao.QuestionDao;
import com.xxxy.dao.StudentAnswerDao;
import com.xxxy.exception.MyException;
import com.xxxy.model.ExaminationPaper;
import com.xxxy.model.Question;
import com.xxxy.model.StudentAnswer;
import com.xxxy.redis.service.RedisService;
import com.xxxy.response.ExamStudent;
import com.xxxy.response.PaperTeachingClass;
import com.xxxy.response.StudentAnswerResponse;
import com.xxxy.response.StudentPaperResponse;
import com.xxxy.service.StudentAnswerService;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author sjh
 * @date 2022/3/5 13:43
 */
@Service
public class StudentAnswerServiceImpl extends ServiceImpl<StudentAnswerDao, StudentAnswer> implements StudentAnswerService {

    @Autowired
    RedisService redisService;

    @Autowired
    ExaminationPaperDao examinationPaperDao;

    @Autowired
    QuestionDao questionDao;

    @Autowired
    StudentAnswerDao studentAnswerDao;

    @Override
    public Boolean putPaper(Integer examId, String studentAccount, Integer teachingClassId, String answerSituation) {
        //answer中存储题目类型->题目答案->题目分数 每个题目存储三个信息
        List<String> answer = null;
        if(!redisService.hasKey("examAnswer"+ examId)) {
            ExaminationPaper examinationPaper = examinationPaperDao.selectById(examId);
            String[] answerArry = examinationPaper.getQuestions().split(",");
            //小节分布
            String[] section = examinationPaper.getSection().split(",");
            //小节分数
            String[] section_score = examinationPaper.getSectionScore().split(",");
            //存储每道题目的分数
            String[] scoreArry = new String[Integer.parseInt(section[section.length-1])];
            int index = 0;
            for(int i = 0; i< section.length;i++){
                while(index <= Integer.parseInt(section[i])-1){
                    scoreArry[index] = section_score[i];
                    index ++;
                }
            }
            List<String> list = new ArrayList<>();
            for(int i =0; i< answerArry.length; i++){
                Question question = questionDao.selectById(Integer.parseInt(answerArry[i]));
                list.add(question.getType().toString());
                list.add(question.getAnswer());
                list.add(scoreArry[i]);
            }
            redisService.set("examAnswer"+ examId.toString(), JSON.toJSONString(list),60 * 60 * 2L);
            answer = list;
        } else {
            answer = JSON.parseArray((String)redisService.get("examAnswer"+ examId),String.class);
        }

        System.out.println(answer.toString());
        String[] studentAnswer = answerSituation.split(",");
        String[] studentScore = new String[studentAnswer.length];
        int j = 0;
        //选择判断的总分
        Double total = 0.0;
        for(int i=0; i< answer.size()/3; i++){
            if(!Objects.equals(answer.get(j), "3")){
                if(Objects.equals(answer.get(j + 1), studentAnswer[i])){
                    studentScore[i] = answer.get(j+2);
                    total += Integer.parseInt(studentScore[i]);
                } else {
                    studentScore[i] = "0";
                }
            } else {
                studentScore[i] = "0";
            }
            j += 3;
        }
        String studentScoreSituation = StringUtils.join(Arrays.asList(studentScore), ',');
        StudentAnswer studentAnswer1 = new StudentAnswer();
        studentAnswer1.setExaminationPaperId(examId);
        studentAnswer1.setStudentAccount(studentAccount);
        studentAnswer1.setTeachingClassId(teachingClassId);
        studentAnswer1.setAnswerSituation(answerSituation);
        studentAnswer1.setScoreSituation(studentScoreSituation);
        studentAnswer1.setTotalScore(total);
        studentAnswer1.setIsExample(0);
        if(studentAnswerDao.insert(studentAnswer1) == 1){
            return true;
        }
        return false;
    }

    @Override
    public Map<String, String> gradeDistribution(String teachingClassIdArray, Integer paperId) {
        LambdaQueryWrapper<StudentAnswer> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(teachingClassIdArray != null){
            String[] teachingClassId = teachingClassIdArray.split(",");
            for(int i = 1; i < teachingClassId.length; i++){
                lambdaQueryWrapper.eq(StudentAnswer::getTeachingClassId, Integer.parseInt(teachingClassId[i]));
                lambdaQueryWrapper.or();
            }
        }
        else {
            lambdaQueryWrapper.eq(StudentAnswer::getExaminationPaperId, paperId);
        }
        List<StudentAnswer> list = studentAnswerDao.selectList(lambdaQueryWrapper);
        Map<String, String> map = new HashMap<>();
        int grade1 = 0; //90-100
        int grade2 = 0; //80-90
        int grade3 = 0; //70-80
        int grade4 = 0; //60-70
        int grade5 = 0; //60以下
        Double maxGrade = 0.0; //最大分数
        Double minGrade = 100.0; //最小分数
        Double totalGrade = 0.0; //总分
        int count = 0; //人数
        for(StudentAnswer studentAnswer : list){
            count ++;
            Double score = studentAnswer.getTotalScore();
            if(score < minGrade){
                minGrade = score;
            }
            if(score > maxGrade){
                maxGrade = score;
            }
            totalGrade += score;

            if(score <= 100 && score >= 90){
                grade1 ++;
            }
            else if(score < 90 && score >= 80){
                grade2 ++;
            }
            else if(score < 80 && score >= 70){
                grade3 ++;
            }
            else if(score < 70 && score >= 60){
                grade4 ++;
            }
            else{
                grade5 ++;
            }
        }
        map.put("level1", String.valueOf(grade1));
        map.put("level2", String.valueOf(grade2));
        map.put("level3", String.valueOf(grade3));
        map.put("level4", String.valueOf(grade4));
        map.put("level5", String.valueOf(grade5));
        map.put("people", String.valueOf(count));
        map.put("maxGrade", String.valueOf(maxGrade));
        map.put("minGrade", String.valueOf(minGrade));
        map.put("averageGrade", String.valueOf(totalGrade/count));
        map.put("pass", String.valueOf((grade1+grade2+grade3+grade4)/count));
        return map;
    }

    @Override
    public StudentAnswerResponse getScoreStudent(String studentAccount, Integer examId) {
        return studentAnswerDao.getScoreStudent(studentAccount, examId);
    }

    @Override
    public List<StudentPaperResponse> getExamPaper(String studentAccount) {
        ArrayList<StudentPaperResponse> studentPaperResponses = new ArrayList<>();

        List<PaperTeachingClass> paperList = examinationPaperDao.selectExamPaperList();
        for (int i = 0; i < paperList.size(); i++) {
            PaperTeachingClass paper = paperList.get(i);
            if (paper.getAdministrative() == 1){
                // 查es_student
                Integer administrativeClass = paper.getAdministrativeClass();
                ExamStudent examStudent = examinationPaperDao.selectStudentByAdministrativeClass(studentAccount, administrativeClass);
                if (examStudent != null){
                    StudentPaperResponse studentPaperResponse = new StudentPaperResponse();
                    studentPaperResponse.setPaperId(paper.getPaperId());
                    studentPaperResponse.setContent(paper.getContent());
                    studentPaperResponse.setExamTime(paper.getExamTime());
                    studentPaperResponse.setEndTime(paper.getEndTime());
                    // 计算题目数量
                    String questions = paper.getQuestions();
                    String[] split = questions.split(",");
                    studentPaperResponse.setQuestionNumber(split.length);
                    studentPaperResponse.setStatus(paper.getStatus());
                    // 课程和学院
                    StudentPaperResponse courseFaculty = examinationPaperDao.getCourseFacultyByPaperId(paper.getPaperId());
                    studentPaperResponse.setCourseName(courseFaculty.getCourseName());
                    studentPaperResponse.setFacultyName(courseFaculty.getFacultyName());
                    studentPaperResponse.setTeachingClassId(paper.getTeachingClassId());
                    studentPaperResponses.add(studentPaperResponse);
                }

            }else {
                // 查es_teachingclass_student
                Integer teachingClassId = paper.getTeachingClassId();
                ExamStudent examStudent = examinationPaperDao.selectStudentByTeachingClassId(studentAccount, teachingClassId);
                if (examStudent != null){
                    StudentPaperResponse studentPaperResponse = new StudentPaperResponse();
                    studentPaperResponse.setPaperId(paper.getPaperId());
                    studentPaperResponse.setContent(paper.getContent());
                    studentPaperResponse.setExamTime(paper.getExamTime());
                    studentPaperResponse.setEndTime(paper.getEndTime());
                    // 计算题目数量
                    String questions = paper.getQuestions();
                    String[] split = questions.split(",");
                    studentPaperResponse.setQuestionNumber(split.length);
                    studentPaperResponse.setStatus(paper.getStatus());
                    // 课程和学院
                    StudentPaperResponse courseFaculty = examinationPaperDao.getCourseFacultyByPaperId(paper.getPaperId());
                    studentPaperResponse.setCourseName(courseFaculty.getCourseName());
                    studentPaperResponse.setFacultyName(courseFaculty.getFacultyName());
                    studentPaperResponse.setTeachingClassId(paper.getTeachingClassId());
                    studentPaperResponses.add(studentPaperResponse);
                }
            }
        }

        return studentPaperResponses;

    }

    @Override
    public String imageUpload(MultipartFile multipartFile) throws IOException {
        if (null == multipartFile || multipartFile.isEmpty()) {
            throw new MyException("上传的文件对象不存在...");
        }
        String fileName = multipartFile.getOriginalFilename(); //得到上传时的文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "/examsystem/images/"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException("上传失败");
        }
        return filePath + fileName;
    }
}
